package com.burgos.inventory;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

	private EditText user, pass;
	private ProgressDialog pDialog;
	private Button submit;
	private JSONParser jsonParser = new JSONParser();
	private static final String LOGIN_URL = "http://test1984.site11.com/remote/login.php";
	
	// responses from PHP server
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";
	/*
	private LoginListener loginListener;
	
	public MainActivity(LoginListener LL){
		this.loginListener = LL;
	}
	*/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		user = (EditText) findViewById(R.id.username);
		pass = (EditText) findViewById(R.id.password);
		submit = (Button) findViewById(R.id.login);
		submit.setOnClickListener(this); 
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login:
			/*Check if the device is connected to the Internet 
			 and if the URL is responding.
			 */
			if(isOnline(this)){
				if(isResponsive()){
					new TryToLogin().execute();
					break;	
				}
			}
		default:
			break;
		}
	}
	
	//Method to check internet availability
	public boolean isOnline(Context context) { 
	    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();    
	    return netInfo != null && netInfo.isConnectedOrConnecting();
	}
	
	//Method to check URL responsiveness
	static public boolean isResponsive() { 
		try {
		    SocketAddress sockaddr = new InetSocketAddress(InetAddress.getByName("31.170.161.136"), 80);
		    // Create an unbound socket
		    Socket sock = new Socket();
		    // This method will block no more than timeoutMs.
		    // If the timeout occurs, SocketTimeoutException is thrown.
		    int timeoutMs = 2000;   // 2 seconds
		    sock.connect(sockaddr, timeoutMs);
		    return true;
		}catch(Exception e){
			return false;
		}
	}
		
	public class TryToLogin extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(MainActivity.this);
			pDialog.setMessage("Try login, please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			int success;
			String username = user.getText().toString();
			String password = pass.getText().toString();
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("username", username));
				params.add(new BasicNameValuePair("password", password));

				// making HTTP request and getting the response
				// SSL
				JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",	params);
				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					// save user data
					SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
					Editor edit = sp.edit();
					edit.putString("username", username);
					edit.commit();
					Intent i = new Intent(MainActivity.this, MainMenu.class);
					finish();
					startActivity(i);
					return json.getString(TAG_MESSAGE);
				} else {
					return json.getString(TAG_MESSAGE);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		protected void onPostExecute(String message) {
			pDialog.dismiss();
			if (message != null) {
				Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
			}
			//loginListener.onSuccess(message);
		}
	}
}
